<template>
    <div class="clockin">
        <titleBar title="打卡签到" />
        <div class="map">
            <div id="clockIn_amap_container" class="map" tabindex="0"></div>   
            <img class="resite-pic" v-on:click="resite" src="@/assets/img/performance/homePage/site.png" />
        </div>
        <div class="flex site">
            <div class="name">约定位置</div>
            <div class="text">{{endSite}}</div>
        </div>
        <div class="button-box">
            <div v-if="clockStatus === 0" class="button noLoadSuccess">加载中</div>
            <div v-if="clockStatus === 1" class="button noLoadSuccess">未在范围内</div>
            <div v-if="clockStatus === 2" class="button" v-on:click="clockIn">点击打卡签到</div>
            <div v-if="clockStatus === 3" class="button noLoadSuccess">请打开定位</div>
            <!-- TODO -->
            <div v-if="clockStatus === 4" class="button">未到时间</div>
        </div>
        <!-- <div class="loading" v-if="clockStatus === 0">
            <van-loading />
        </div> -->
    </div>
</template>
<script>
// TODO 用户有篡改当前位置的可能性
// TODO 图标未换
// TODO 跟踪位置.
import titleBar from '@/components/title_bar/index.vue'
import {clockInDistance} from './constant.js'
import { getuserUid } from '@/utils/auth'
import { AMAPKEY, asyncLoadAMAP, Getsite } from '@/utils/amap.js'

import {
  setUserLogin,
  setVersionNo,
  setToken,
  getToken,
  getRole,
  setuserUid,
  setRole,
  setPassword,
  getUserLogin
} from "@/utils/auth.js";

let isRuning = false
let vm
let SimpleMarker
let map
let mySite
let customerSite
let getCustomStatus = 0
let customHandle = function(_e) {
    let e
    if(_e instanceof Array){
        e = {
            lng: _e[0],
            lat: _e[1]
        }
    }else if(typeof _e === typeof {}){
        e = _e
    }else{
        console.log('异常')
        console.log(e)
        return
    }
    console.log('客户位置QAQ', e)
    let img = require('@/assets/img/public/c-site.png')
    var marker =  getMarker(
        e,
        `<img style="width: 25px" src="${img}" />`,
        '客'
    )
    map.add(marker)
    getAmapDistance(mySite, customerSite)
    customerSite = JSON.parse(JSON.stringify(e))
}
let getAmapDistance = function(p1, p2) {
    // console.log(p1, p2)
    let dis = AMap.GeometryUtil.distance([p1.lng, p1.lat], [p2.lng, p2.lat])
    console.log('dis')
    console.log(dis)
    console.log('定位范围')
    console.log((getUserLogin() || {}).distance || clockInDistance)
    if(dis <= ((getUserLogin() || {}).distance || clockInDistance)){
        vm.clockStatus = 2
    }else{
        // vm.$toast('未在范围内,无法打卡')
        vm.clockStatus = 1
    }
}
let getMarker = (center, content, title) => {
    return new AMap.Marker({
        position: new AMap.LngLat(+center.lng, +center.lat),
        offset: new AMap.Pixel(-10, -40),
        content,
        title,
    })
}
let loadMap = async (site) => {
    let params = {
        zoom: 16,
    }
    let  _center
    try {
        _center = await Getsite() 
        // // 小鹿快跑
        // _center = [113.947334,22.545055]
        // _center = [113.948312, 22.545767]
    } catch (error) {
        vm.$toast(error)
        map = true
        vm.clockStatus = 3
        return
    }
    params.center = _center
    map = new AMap.Map('clockIn_amap_container', params)
    mySite = {
            lng: _center[0],
            lat: _center[1]
    }
    // map.getCenter()
    let img = require('@/assets/img/public/my-site.png')
    var marker = getMarker(
        {
            lng: _center[0],
            lat: _center[1]
        },
        `<img style="width: 25px" src="${img}" />`,
        '我'
    )
    map.add(marker)
    // if(getCustomStatus === 1){
        customHandle.bind(vm)(customerSite)
    // }
    console.log(map)
}
export default {
    components: {
        titleBar
    },
    data(){
        return {
            // 0 加载中 1 未在范围  2 在范围内
            clockStatus: 0,
            // 参数
            orderUid: '',
            // 目标位置
            endSite: '--',
        }
    },
    created(){
        window.map_callback = () => {
            if(!isRuning){
                return
            }
            initAMapUI()
            loadMap()    
        }
        isRuning = true
        this.orderUid = this.$route.query.orderUid
        console.log(this.orderUid)
        if(!this.orderUid){
            this.$toast('URL参数错误')
            return
        }
        this.initAmap()
    },
    methods: {
        initAmap(){
            vm = this
            asyncLoadAMAP() 
            this.getCustomerSite(this.handleCustomerSite)
        },
        async getCustomerSite(cb){
            let params = {
                orderUid: this.orderUid,
                userUid: getuserUid(),
            }
            let customerSiteResponse
            try{
                customerSiteResponse = await HTTP('clockinInfo', params)
                if(customerSiteResponse.code !== 200){
                    this.$toast(customerSiteResponse.msg || '服务器异常')
                    return
                }
            }catch(e){
                this.$toast('服务器异常')
            }
            // customerSiteResponse.data // 赋值位置
            // 华新(地铁站)
            // let res = [114.086654,22.548981]
            // 赛格
            // let res = [114.087608,22.547292]
            // 研祥科技大厦
            // let res = [113.932901,22.54219]
            let res = [customerSiteResponse.data.longitude, customerSiteResponse.data.latitude]
            this.endSite = customerSiteResponse.data.address
            // TODO clockStatus = 4
            cb && cb(res)
        },
        handleCustomerSite(e){
            console.log('---处理位置---')
            customerSite = {
                lng: e[0],
                lat: e[1],
            }
            // 确保map已经建立
            if(map){
                customHandle.bind(this)(e)
            }else{
                setTimeout(() => {
                    // 递归加载
                    this.handleCustomerSite(e)
                }, 1e3)
                getCustomStatus += 1
            }
        },
        cb(positionResult){
            console.log(positionResult)
        },
        resite(){
            loadMap()
        },
        async clockIn(){
            console.log('打卡')
            if(!this.clockStatus === 0){
                this.$toast('加载中')
                return 
            }
            let params = {
                bUserUid: getuserUid(),
                orderUid: this.orderUid,
                longitude: mySite.lng,
                latitude: mySite.lat,
            }
            console.log(params)
            let clockInResponse
            try {            
                clockInResponse = await HTTP('bUserCheckIn', params)
                if(clockInResponse.code !== 200){
                    this.$toast(clockInResponse.msg || '服务器错误')
                    return
                }
            } catch (error) {
                this.$toast('服务器异常')
            }
            // TODO 可能需要转跳页面，需要从参数传入
            this.$toast('打卡成功')
            setTimeout(() => {
                this.$router.go(-1)
            }, 1e3)
        }
    },
    destroyed(){
        map.destroy()
        isRuning = false
    }
}
</script>
<style lang="scss" scoped>
$botton-height: 1.60rem;
.clockin{
    .loading{
        z-index: 20;
        position: fixed;
        top: 0px;
        left: 0px;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, .5);
        >div{
            position: absolute;
            top: 50%;
            left: 50%;
        }
    }
    .resite-pic{
        position: fixed;
        bottom: 3.8rem;
        left: .12rem;
        width: 1.04rem;
        height: 1.04rem;
    }
    #clockIn_amap_container{
        position: fixed;
        top: .9rem;
        left: 0px;
        width: 100vw;
        height: calc(100vh - .9rem - 1.48rem - 1.6rem);
    }
    .site{
        background: #fff;
        position: fixed;
        bottom: 1.6rem;
        height: 1.48rem;
        width: 100%;
        font-size: .28rem;
        padding-top: .36rem;
        box-sizing: border-box;
        .name{
            width: 1.76rem;
            color: $color-text;
            text-indent: .24rem;
        }
        .text{
            width: 5.5rem;
        }
    }
    .button-box{
        position: fixed;
        width: 100%;
        bottom: 0px;
        background-color: rgba(255,255,255,.79);
        height: $botton-height;
        box-shadow:0px 2px 8px 4px rgba(216,216,216,0.5);
        // opacity:0.7994;
        z-index: 9;
        .button{
            width: 7.02rem;
            height: .88rem;
            background: $color-primary;
            border-radius: .1rem;
            margin: auto;
            text-align: center;
            line-height: .88rem;
            color: #fff;
            font-size: .28rem;
            margin-top: .35rem;
        }
        .noLoadSuccess{
            opacity: .5;
        }
    }
}
</style>
